from django.shortcuts import render_to_response
from deduit.main.models import Visitor
from deduit.main.models import UserPrefs
from google.appengine.api import urlfetch
from  google.appengine.ext import db
from xml.dom import minidom
from datetime import datetime
from urllib import quote
import hashlib
import urllib
import utils
from django.http import HttpResponse
from google.appengine.api import users
from django.http import HttpResponseRedirect
from datetime import timedelta
from datetime import datetime, date, time

exploretime = timedelta(hours=-8, days=-1)

def main(request, page='1', day='%02d' % (datetime.now()+exploretime).day, month='%02d' % (datetime.now()+exploretime).month, year=(datetime.now()+exploretime).year):
    url = "http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=4ffd08ef36219cd952ccbd153052f833&extras=url_m,url_s&per_page=20&page=%s&date=%s-%s-%s" % (page, year, month, day)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)
    
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):               
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
        
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'photos':photos, 'api_sig':  api_sig, 'nextPage':'/explore/interesting/%s/%s/%s/page%d' % (year, month, day, int(page)+1)})

def friendsphotos(request, page='1'):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url('http://flickrforsalaryman.appspot.com'+request.path))
    
    userprefs = UserPrefs().getcurrentuser()
    sig_string = 'c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833auth_token%scount50extrasdate_upload,date_taken,owner_name,url_m,url_smethodflickr.photos.getContactsPhotossingle_photo1' % userprefs.token
    api_sig = hashlib.md5(sig_string).hexdigest()
    url = "http://api.flickr.com/services/rest/?method=flickr.photos.getContactsPhotos&api_key=4ffd08ef36219cd952ccbd153052f833&extras=date_upload,date_taken,owner_name,url_m,url_s&count=50&auth_token=%s&api_sig=%s&single_photo=1" % (userprefs.token, api_sig)
    
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)
    
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
    
    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'photos':photos, 'nextPage':'/photos/friends/page%d' % (int(page)+1)})

def usernamephotos(request, username='me', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/photos/'+username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('id')
        return userphotos(request, nsid, username, page)
    #find by username
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('nsid')
        return userphotos(request, nsid, username, page)
    return userphotos(request, username, page)

def userphotos(request, nsid='me', username = '', page=1):    
    visitors = Visitor.all()
    visitors.order("-added_on")
    url = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=4ffd08ef36219cd952ccbd153052f833&&extras=description,date_upload,path_alias,tags,owner_name,url_m,url_s&per_page=20&user_id=%s&page=%s" % (nsid, page)
    flickrResponse = urlfetch.fetch(url, deadline=33)  

    xmldoc = minidom.parseString(flickrResponse.content)
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
         
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'api_sig':  api_sig, 'photos':photos, 'username':username if username is not '' else nsid, 'nextPage':'/photos/%s/page%d' % (username if username is not '' else nsid, int(page)+1)})

def popularusernamephotos(request, username='me', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/photos/'+username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('id')
        return popularuserphotos(request, nsid, username, page)
    #find by username
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('nsid')
        return popularuserphotos(request, nsid, username, page)
    return popularuserphotos(request, username, page)

def popularuserphotos(request, nsid='me', username = '', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=4ffd08ef36219cd952ccbd153052f833&&extras=description,date_upload,path_alias,tags,owner_name,url_m,url_s&sort=interestingness-desc&per_page=20&user_id=%s&page=%s" % (nsid, page)
    flickrResponse = urlfetch.fetch(url, deadline=33)  

    xmldoc = minidom.parseString(flickrResponse.content)
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'api_sig':  api_sig, 'photos':photos, 'username':username if username is not '' else nsid, 'nextPage':'/photos/%s/popular-interesting/page%d' % (username if username is not '' else nsid, int(page)+1)})

def favoritesusernamephotos(request, username='me', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/photos/'+username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('id')
        return favoritesuserphotos(request, nsid, username, page)
    #find by username
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('nsid')
        return favoritesuserphotos(request, nsid, username, page)
    return favoritesuserphotos(request, username, page)

def favoritesuserphotos(request, nsid='me', username = '', page=1):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url('http://flickrforsalaryman.appspot.com'+request.path))
    
    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
    userprefs = q.get()    
    token = userprefs.token
    apiSigString = "c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833auth_token%sextrasurl_m,url_smethodflickr.favorites.getListpage%sper_page20user_id%s" % (token, page, nsid)
    api_sig = hashlib.md5(apiSigString).hexdigest()
    
    params = urllib.urlencode({
        'method': 'flickr.favorites.getList',
        'api_key': '4ffd08ef36219cd952ccbd153052f833',
        'page': page,        
        'user_id': nsid,        
        'page': page,   
        'per_page': 20,     
        'auth_token': token,
        'api_sig': api_sig,
        'extras': 'url_m,url_s'
    })
    url = "http://api.flickr.com/services/rest/?%s" % params
    flickrResponse = urlfetch.fetch(url, deadline=33)  

    xmldoc = minidom.parseString(flickrResponse.content)
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'api_sig':  api_sig, 'photos':photos, 'username':username if username is not '' else nsid, 'nextPage':'/photos/%s/favorites/page%d' % (username if username is not '' else nsid, int(page)+1)})

def usernamesets(request, username='me', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/photos/'+username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('id')
        return usersets(request, nsid, username, page)
    #find by username
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('nsid')
        return usersets(request, nsid, username, page)
    return usersets(request, username, page)

def usersets(request, nsid='me', username = '', page=1):
    visitors = Visitor.all()
    visitors.order("-added_on")
    url = "http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=4ffd08ef36219cd952ccbd153052f833&user_id=%s" % nsid    
    flickrResponse = urlfetch.fetch(url, deadline=33)  

    xmldoc = minidom.parseString(flickrResponse.content)
    sets = []
    for node in xmldoc.getElementsByTagName('photoset'):        
        sets.append({       
            'id': node.getAttribute('id'),
            'primary': node.getAttribute('primary'),
            'secret': node.getAttribute('secret'),
            'server': node.getAttribute('server'),
            'farm': node.getAttribute('farm'),
            'photos': node.getAttribute('photos'),
            'videos': node.getAttribute('videos'),
            'title': utils.getText(node.getElementsByTagName("title")[0].childNodes).replace("\n", "<br />"),
            'description': utils.getText(node.getElementsByTagName("description")[0].childNodes).replace("\n", "<br />"),
            'localurl': '/photos/' + (username if username is not '' else nsid) + '/sets/' +  node.getAttribute('id')
    })
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'api_sig':  api_sig, 'sets':sets, 'username':username if username is not '' else nsid, 'nextPage':'/photos/%s/page%d' % (username if username is not '' else nsid, int(page)+1)})

def usernamesetsphotos(request, username='me', setid='', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/photos/'+username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('id')
        return usersetsphotos(request, nsid, username, setid, page)
    #find by username
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('nsid')
        return usersetsphotos(request, nsid, username, setid, page)
    return usersetsphotos(request, username, setid, page)

def usersetsphotos(request, nsid='me', username = '', setid='', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=4ffd08ef36219cd952ccbd153052f833&&extras=description,date_upload,path_alias,tags,owner_name,url_m,url_s&per_page=20&photoset_id=%s&page=%s" % (setid, page)
    flickrResponse = urlfetch.fetch(url, deadline=33)  

    xmldoc = minidom.parseString(flickrResponse.content)
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'api_sig':  api_sig, 'photos':photos, 'username':username if username is not '' else nsid, 'nextPage':'/photos/%s/sets/%s/page%d' % (username if username is not '' else nsid, setid, int(page)+1)})

def photoByUsernameAndID(request, username='me', photoid=1):
    #find by url
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/photos/'+username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('id')
        return photoByID(request, nsid, photoid)
    #find by username
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(username)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('user'):
        nsid = node.getAttribute('nsid')
        return photoByID(request, nsid, photoid)
    return photoByID(request, username, photoid)	

def photoByID(request, nsid='me', photoid='0'):
    infoDoc = utils.getInfoDoc(photoid)
    exif = utils.getExifDoc(photoid)
    
    commentUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&api_key=4ffd08ef36219cd952ccbd153052f833&&photo_id=%s" % photoid        
    commentDoc = minidom.parseString(urlfetch.fetch(commentUrl, deadline=33).content)
    wita = timedelta(hours=8)
    
    photo ={       
        'id': photoid,
        'username': infoDoc.getElementsByTagName("owner")[0].getAttribute('username') if infoDoc.getElementsByTagName("owner")[0].getAttribute('username') is not '' else infoDoc.getElementsByTagName("owner")[0].getAttribute('owner'),
        'secret': infoDoc.getElementsByTagName("photo")[0].getAttribute('secret'),
        'server': infoDoc.getElementsByTagName("photo")[0].getAttribute('server'),
        'farm': infoDoc.getElementsByTagName("photo")[0].getAttribute('farm'), 
        'views': infoDoc.getElementsByTagName("photo")[0].getAttribute('views'),         
        'title': utils.getText(infoDoc.getElementsByTagName("title")[0].childNodes),
        'tags': utils.getTags(infoDoc),
        'date': (datetime.fromtimestamp(int(infoDoc.getElementsByTagName("dates")[0].getAttribute('posted'))) + wita).strftime("%A, %d %B %Y"),
        'time': (datetime.fromtimestamp(int(infoDoc.getElementsByTagName("dates")[0].getAttribute('posted'))) + wita).strftime("%I:%M%p"),  
        'ownername': infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') if infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') != "" else infoDoc.getElementsByTagName("owner")[0].getAttribute('username'),          
        'description': utils.getText(infoDoc.getElementsByTagName("description")[0].childNodes).replace("\n", "<br />"),
        'url': utils.getText(infoDoc.getElementsByTagName("url")[0].childNodes),
        'nsid': infoDoc.getElementsByTagName("owner")[0].getAttribute('nsid'),
        'comments': utils.getText(infoDoc.getElementsByTagName("comments")[0].childNodes),
        'exif': utils.exifData(exif),
        'location': utils.getLocation(infoDoc)
    }
    
    username = ''
    nsid = photo['nsid']
            
    comments = []
    for comment in commentDoc.getElementsByTagName('comment'):        
        comments.append({       
            'id': comment.getAttribute('id'),
            'author': comment.getAttribute('author'),
            'authorname': comment.getAttribute('authorname'),
            'datecreate': datetime.fromtimestamp(int(comment.getAttribute('datecreate'))).strftime("%d %B %Y %I:%M%p"),
            'permalink': comment.getAttribute('permalink'),
            'body': utils.getText(comment.childNodes).replace("\n", "<br />")            
        })            
    return render_to_response('main/details.html', {'userprefs': UserPrefs().getcurrentuser(), 'username':username if username is not '' else nsid, 'photo':photo, 'comments':comments, 'nextPage':'/photos/%s/page%d' % (nsid, int(1)+1)})

def groupnamephotos(request, groupname='me', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupGroup&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/groups/'+groupname)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('group'):
        groupid = node.getAttribute('id')
        return groupphotos(request, groupid, groupname, page)
    #find by groupname
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(groupname)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('group'):
        groupid = node.getAttribute('id')
        return groupphotos(request, groupid, groupname, page)
    return groupphotos(request, groupname, page)

def groupphotos(request, groupid='me', groupname = '', page=1):    
    url = "http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&api_key=4ffd08ef36219cd952ccbd153052f833&extras=description,date_upload,path_alias,tags,owner_name,url_m,url_s&per_page=20&group_id=%s&page=%s" % (groupid, page)
    flickrResponse = urlfetch.fetch(url, deadline=33)  

    xmldoc = minidom.parseString(flickrResponse.content)
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
         
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'api_sig':  api_sig, 'photos':photos, 'groupname':groupname if groupname is not '' else groupid, 'nextPage':'/groups/%s/pool/page%d' % (groupname if groupname is not '' else groupid, int(page)+1)})

def populargroupnamephotos(request, groupname='me', page=1):
    url = "http://api.flickr.com/services/rest/?method=flickr.urls.lookupGroup&api_key=4ffd08ef36219cd952ccbd153052f833&url=%s" % quote('flickr.com/groups/'+groupname)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('group'):
        groupid = node.getAttribute('id')
        return populargroupphotos(request, groupid, groupname, page)
    #find by groupname
    url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=4ffd08ef36219cd952ccbd153052f833&username=%s" % quote(groupname)
    flickrResponse = urlfetch.fetch(url, deadline=33)
    xmldoc = minidom.parseString(flickrResponse.content)    
    for node in xmldoc.getElementsByTagName('group'):
        groupid = node.getAttribute('id')
        return populargroupphotos(request, groupid, groupname, page)
    return populargroupphotos(request, groupname, page)

def populargroupphotos(request, groupid='me', groupname = '', page=1):    
    url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=4ffd08ef36219cd952ccbd153052f833&&extras=description,date_upload,path_alias,tags,owner_name,url_m,url_s&sort=interestingness-desc&per_page=20&group_id=%s&page=%s" % (groupid, page)
    flickrResponse = urlfetch.fetch(url, deadline=33)  

    xmldoc = minidom.parseString(flickrResponse.content)
    photos = []
    for node in xmldoc.getElementsByTagName('photo'):
        photos.append(utils.getPhotoDetails(node.getAttribute('id'), node))
         
    api_sig = hashlib.md5("c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833permswrite").hexdigest()

    return render_to_response('main/index.html', {'userprefs': UserPrefs().getcurrentuser(), 'api_sig':  api_sig, 'photos':photos, 'groupname':groupname if groupname is not '' else groupid, 'nextPage':'/groups/%s/popular-interesting/page%d' % (groupname if groupname is not '' else groupid, int(page)+1)})

def login(request):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url('http://flickrforsalaryman.appspot.com'+request.path))
    frob = request.GET.get('frob')
    apiSigString = "c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833frob%smethodflickr.auth.getToken" % frob
    api_sig = hashlib.md5(apiSigString).hexdigest()
    tokenUrl = "http://api.flickr.com/services/rest/?method=flickr.auth.getToken&api_key=4ffd08ef36219cd952ccbd153052f833&frob=%s&api_sig=%s" % (frob, api_sig)        
    tokenDoc = minidom.parseString(urlfetch.fetch(tokenUrl, deadline=33).content)
    #tokenDoc = minidom.parseString('<rsp stat="ok"><auth><token>72157625106384102-066571d12b6e0511</token><perms>write</perms><user nsid="44861801@N07" username="Fajar Nurdiansyah" fullname="fajar nurdiansyah"/></auth></rsp>')
     
    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
    userprefs = q.get()
    if not userprefs:
        userprefs = UserPrefs()
    userprefs.user = user
    userprefs.token = utils.getText(tokenDoc.getElementsByTagName("token")[0].childNodes)
    userprefs.nsid = tokenDoc.getElementsByTagName("user")[0].getAttribute('nsid')
    userprefs.username = tokenDoc.getElementsByTagName("user")[0].getAttribute('username')
    userprefs.fullname = tokenDoc.getElementsByTagName("user")[0].getAttribute('fullname')
    userprefs.put()

    return main(request)#render_to_response('main/details.html', {'frob':token, 'api_sig':api_sig, 'token':user})

def auth(request):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url('http://flickrforsalaryman.appspot.com/auth'))
    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
    
    userprefs = q.get()
    if not userprefs:
        userprefs = UserPrefs()
    userprefs.user = user
    userprefs.put()
    return main(request)

def comment(request):    
    user = users.get_current_user()
    if not user:
        return HttpResponse("Must login to comment", mimetype="text/plain")  

    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
    userprefs = q.get()
    comment = request.POST['comment']
    photoId = request.POST['photoid']
    token = userprefs.token
    #tokenDoc = minidom.parseString('<rsp stat="ok"><auth><token>72157625106384102-066571d12b6e0511</token><perms>write</perms><user nsid="44861801@N07" username="Fajar Nurdiansyah" fullname="fajar nurdiansyah"/></auth></rsp>')
    #token = getText(tokenDoc.getElementsByTagName("token")[0].childNodes)  
    
    apiSigString = "c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833auth_token%scomment_text%smethodflickr.photos.comments.addCommentphoto_id%s" % (token, comment, photoId)
    api_sig = hashlib.md5(apiSigString).hexdigest()
    
    params = urllib.urlencode({
        'method': 'flickr.photos.comments.addComment',
        'api_key': '4ffd08ef36219cd952ccbd153052f833',
        'photo_id': photoId,
        'comment_text': comment,
        'auth_token': token,
        'api_sig': api_sig
    })
    commentResult = urllib.urlopen("http://api.flickr.com/services/rest/", params).read()# + params
    if 'User is posting comments too fast' in commentResult:
        commentResult = "User is posting comments too fast"
    elif 'Blank comment' in commentResult:
        commentResult = "Comment text can not be blank"
    else:
        commentResult = "Comment posted"
    response = HttpResponse(commentResult, mimetype="text/plain")         

    return response #render_to_response('main/details.html', {'frob':commentResult, 'api_sig':apiSigString, 'token':params})

def fave(request):    
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url('http://flickrforsalaryman.appspot.com'+request.path))

    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
    userprefs = q.get()    
    photoId = request.POST['photoid']
    token = userprefs.token
    
    apiSigString = "c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833auth_token%smethodflickr.favorites.addphoto_id%s" % (token, photoId)
    api_sig = hashlib.md5(apiSigString).hexdigest()
    
    params = urllib.urlencode({
        'method': 'flickr.favorites.add',
        'api_key': '4ffd08ef36219cd952ccbd153052f833',
        'photo_id': photoId,        
        'auth_token': token,
        'api_sig': api_sig
    })
    faveResult = urllib.urlopen("http://api.flickr.com/services/rest/", params).read()
    faveDoc = minidom.parseString(faveResult)
    errors = faveDoc.getElementsByTagName("err")
    if errors.length > 0:
        apiSigString = "c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833auth_token%smethodflickr.favorites.removephoto_id%s" % (token, photoId)
        api_sig = hashlib.md5(apiSigString).hexdigest()
        
        params = urllib.urlencode({
            'method': 'flickr.favorites.remove',
            'api_key': '4ffd08ef36219cd952ccbd153052f833',
            'photo_id': photoId,        
            'auth_token': token,
            'api_sig': api_sig
        })
        faveResult = urllib.urlopen("http://api.flickr.com/services/rest/", params).read()
        response = HttpResponse('unfave', mimetype="text/plain")
    else:
        response = HttpResponse('fave', mimetype="text/plain")         

    return response #render_to_response('main/details.html', {'frob':commentResult, 'api_sig':apiSigString, 'token':params})
  
